package com.yangda.example.framework;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.serializer.SerializerFeature;
import com.alibaba.fastjson.support.spring.FastJsonHttpMessageConverter;
import com.yangda.example.framework.model.Response;
import com.yangda.example.utils.DateUtils;
import org.springframework.http.HttpOutputMessage;
import org.springframework.http.converter.HttpMessageNotWritableException;

import java.io.IOException;
import java.io.OutputStream;

/**
 * @文件名 :CustomJsonHttpMessageConverter.java
 * @创建人 :carl
 * @时间 :2016年8月1日 下午2:44:54
 * @描述 :自定义统一返回格式
 */
public class CustomJsonHttpMessageConverter extends FastJsonHttpMessageConverter {

    @Override
    protected void writeInternal(Object obj, HttpOutputMessage outputMessage)
            throws IOException, HttpMessageNotWritableException {

        OutputStream out = outputMessage.getBody();

        JSON.DEFFAULT_DATE_FORMAT = DateUtils.YYYY_MM_DD_HH_MM_SS;

        //解决@ref
        SerializerFeature feature = SerializerFeature.DisableCircularReferenceDetect;


        //解决null对象
        SerializerFeature writeMapNullValue = SerializerFeature.WriteMapNullValue;

        //解决""字段
        SerializerFeature writeNullStringAsEmpty = SerializerFeature.WriteNullListAsEmpty;

        //解决时间long转成固定时间格式
        SerializerFeature writeDateUseDateFormat = SerializerFeature.WriteDateUseDateFormat;

        //默认返回成功
        Response response = new Response(ResultCode.SCUCESS);
        response.setContent(obj);

        String text = JSON.toJSONString(response, feature, writeMapNullValue, writeNullStringAsEmpty, writeDateUseDateFormat);

        byte[] bytes = text.getBytes(super.getCharset());
        out.write(bytes);
        out.flush();
    }

}
